#ifndef _MEM_POOL_H_
#define _MEM_POOL_H_

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define ULONG			unsigned long
#define USHORT			unsigned short
#define MEM_ALIGNMENT	4

struct memoryblock;

class memorypool
{
	public:
		memorypool(USHORT _unitsize, USHORT _initsize = 2048, USHORT _growsize = 1024);
		~memorypool();

	public:
		void *alloc();
		void release(void *p);

	private:
		memoryblock *m_mb;
		USHORT		m_initsize;
		USHORT		m_unitsize;
		USHORT		m_growsize;
};

struct memoryblock
{
	USHORT m_size;	//total
	USHORT m_free;
	USHORT m_first;
	memoryblock *m_pnext;
	char m_data[1];

	void *operator new (size_t, USHORT p_size, USHORT p_unitsize)
	{
		return ::operator new(sizeof(memoryblock) + p_size * p_unitsize);
	}

	void operator delete (void *p, size_t)
	{
		::operator delete(p);
		p = NULL;
	}

	memoryblock(USHORT p_size, USHORT p_unitsize):m_size(p_size * p_unitsize), m_free(p_size - 1), m_first(1), m_pnext(NULL)
	{
		char *pdata = m_data;

		for (int i = 1; i < p_size; i++)
		{
			*reinterpret_cast<USHORT *>(pdata) = i;
			pdata += p_unitsize;
		}
	}

	~memoryblock() {}
};

#endif

